import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_scan_tool/bloc/device/device_bloc.dart';
import 'package:flutter_scan_tool/bloc/tool/tool_bloc.dart';
import 'package:flutter_scan_tool/bloc/tool/tool_event.dart';
import 'package:flutter_scan_tool/models/antenna.dart';
import 'package:flutter_scan_tool/models/app_theme.dart';
import 'package:flutter_scan_tool/page/temperature_humidity.dart';
import 'package:flutter_scan_tool/page/tool_scan.dart';
import 'package:flutter_scan_tool/utils/flash_helper.dart';
import 'package:flutter_scan_tool/widget/floating_modal.dart';
import 'package:flutter_scan_tool/widget/title_view.dart';
import 'package:flutter_svg/svg.dart';
import 'package:web_socket_channel/io.dart';

import 'device_setting.dart';
import 'selector_storage.dart';
import 'tool_info_page.dart';
import 'tool_sum_list_view.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  final ScrollController _scrollController = ScrollController();
  AnimationController? animationController;
  Animation<double>? animation;
  List<Widget> listViews = [];

  // final List<ToolData> toolList = ToolData.toolList;

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 1000), vsync: this);
    addListData();
    toolBloc = context.read<ToolBloc>();
    super.initState();
  }

  ToolBloc? toolBloc;
  IOWebSocketChannel? channel;
  Timer? tmr;
  bool isShowStorageView = false;
  bool reload=false;

  @override
  void dispose() {
    animationController?.dispose();
    channel?.sink.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBody: true,
      resizeToAvoidBottomInset: false,
      backgroundColor: AppTheme.appTheme.containerBackgroundColor(),
      appBar: appBar(context),
      body: BlocConsumer<DeviceBloc, DeviceState>(
        listener: (context, state) {
          if (state.isStorageConfig == StorageStatus.unConfig) {
            if (!isShowStorageView) {
              showStorageDialog(context);
              isShowStorageView = true;
            }
          }
          if (state.readFinish) {
            if(!reload) {
              toolBloc!.add(ToolLoadEvent({}));
              reload=true;
            }
          }else{
            reload=false;
          }
          if (state.isReading) {
            if (state.isConnect == ConnectStatus.connected) {
              var tempList=toolBloc!.toolDataList;

              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) {
                  return ToolScanPage(list: tempList);
                }),
              );
            } else {
              FlashHelper.toast(
                  context, '检测未连接设备,无法进入工具操作界面', MessageType.alert);
            }
          }
        },
        builder: (context, state) {
          return body();
        },
        // ),
      ),
    );
  }

  int count=0;

  AppBar appBar(BuildContext context) {
    return AppBar(
      elevation: 0,
      centerTitle: true,
      title: BlocBuilder<DeviceBloc, DeviceState>(builder: (_, state) {
        return Text(
          state.storageName,
          style: const TextStyle(
              fontFamily: 'times',
              fontSize: 18,
              fontWeight: FontWeight.w200,
              color: Colors.white),
        );
      }),
      leading: const Text(
        '',
        style: TextStyle(fontSize: 20, color: Colors.white),
      ),
      actions: [
        PopupMenuButton<String>(
          itemBuilder: (BuildContext context) => [
            selectView('image/storageConfig.svg', '仓库设置', 'A'),
            selectView('image/deviceConfig.svg', '射频设置', 'B'),
          ],
          offset: const Offset(0, 30),
          color: Colors.blue,
          elevation: 5,
          padding: const EdgeInsets.all(2),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(20)),
          ),
          onSelected: (String action) {
            switch (action) {
              case 'A':
                showStorageDialog(context);
                break;
              case 'B':
                FocusScope.of(context).requestFocus(FocusNode());
                var bloc = context.read<DeviceBloc>();
                showDeviceView(context, bloc.state.antennaList);
                break;
            }
          },
        )
      ],
    );
  }

  PopupMenuItem<String> selectView(String iconPath, String text, String id) {
    return PopupMenuItem<String>(
      value: id,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          SvgPicture.asset(
            iconPath,
            width: 20,
            color: Colors.white,
          ),
          Text(
            text,
            style: const TextStyle(
              fontSize: 16,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  Widget body() {
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              colors: [Color(0xFF2196F3), Color(0xFF2196F3)],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight)),
      child: Stack(
        children: [
          getMainListView(),
        ],
      ),
    );
  }

  void showStorageDialog(BuildContext context) async {
    await showDialog(
        context: context,
        builder: (_) {
          return const StorageView();
        });
  }

  void showDeviceView(BuildContext context, List<AntennaData> bloc) async {
    await showFloatingModalBottomSheet(
        context: context,
        barrierColor: Colors.black87,
        builder: (context) {
          return DeviceSetting(
            antennaList: bloc,
          );
        });
  }

  Widget getMainListView() {
    return FutureBuilder<bool>(
      future: geFutbooData(),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        if (!snapshot.hasData) {
          return const SizedBox();
        } else {
          return ListView.builder(
              controller: _scrollController,
              scrollDirection: Axis.vertical,
              itemCount: listViews.length,
              itemBuilder: (BuildContext context, int index) {
                animationController?.forward();
                return listViews[index];
              });
        }
      },
    );
  }

  Widget getButtonUI() {
    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16),
      child: BlocBuilder<DeviceBloc, DeviceState>(
        builder: (context, state) {
          return Row(
            children: [
              getUI(
                  '射频状态:${state.isConnect == ConnectStatus.connected ? '连接' : '断开'}',
                  state.isConnect == ConnectStatus.connected),
              const SizedBox(
                width: 50,
              ),
              getUI(
                  '网络状态:${state.socketConnectStatus == ConnectStatus.connected ? '连接' : '断开'}',
                  state.socketConnectStatus == ConnectStatus.connected),
            ],
          );
        },
      ),
    );
  }

  Widget getUI(String text, bool status) {
    return Expanded(
      child: AnimatedContainer(
        duration: const Duration(seconds: 1),
        curve: Curves.fastOutSlowIn,
        margin: const EdgeInsets.only(left: 10, right: 10, top: 10),
        decoration: BoxDecoration(
            color: status
                ? Colors.greenAccent.withOpacity(0.8)
                : Colors.red.withOpacity(0.8),
            borderRadius: const BorderRadius.all(Radius.circular(24.0)),
            border: Border.all(color: Colors.lightBlue)),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            splashColor: Colors.white24,
            borderRadius: const BorderRadius.all(Radius.circular(24.0)),
            child: Padding(
              padding: const EdgeInsets.only(
                  top: 12, bottom: 12, left: 18, right: 18),
              child: Center(
                child: Text(
                  text,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    fontFamily: 'Montserrat',
                      fontWeight: FontWeight.normal,
                      fontSize: 20,
                      letterSpacing: 0.27,
                      color: status ? Colors.white : Colors.black),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  void addListData() {
    const int count = 6;
    listViews.add(TitleView(
      titleTxt: '状态信息',
      subTxt: '',
      animation: Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(
          parent: animationController!,
          curve: const Interval((1 / count) * 0, 1.0,
              curve: Curves.fastOutSlowIn))),
      animationController: animationController,
      callback: () {},
    ));
    listViews.add(getButtonUI());
    listViews.add(TitleView(
      titleTxt: '温湿度信息',
      subTxt: '',
      animation: Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(
          parent: animationController!,
          curve: const Interval((1 / count) * 0, 1.0,
              curve: Curves.fastOutSlowIn))),
      animationController: animationController,
      callback: () {},
    ));
    listViews.add(TemperatureHumidityView(
      animation: Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(
          parent: animationController!,
          curve: const Interval((1 / count) * 1, 1.0,
              curve: Curves.fastOutSlowIn))),
      animationController: animationController,
    ));
    listViews.add(TitleView(
      titleTxt: '工具信息',
      subTxt: '工具列表',
      animation: Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(
          parent: animationController!,
          curve: const Interval((1 / count) * 2, 1.0,
              curve: Curves.fastOutSlowIn))),
      animationController: animationController,
      callback: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) {
            return const ToolInfoPage();
          }),
        );
      },
    ));
    listViews.add(ToolSumListView(
      mainScreenAnimationController: animationController,
      mainScreenAnimation: Tween<double>(begin: 0.0, end: 1.0).animate(
          CurvedAnimation(
              parent: animationController!,
              curve: const Interval((1 / count) * 3, 1.0,
                  curve: Curves.fastOutSlowIn))),
    ));
  }

  Future<bool> geFutbooData() async {
    await Future<dynamic>.delayed(const Duration(milliseconds: 50));
    return true;
  }
}
